//
//  AppDelegate.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/4/19.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "AppDelegate.h"
#import "KLLoginViewController.h"
#import "JRToast.h"
#import "KLHelp.h"
#import "KLOpenClockViewController.h"
#import "KLLeftTableViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "KLHttpAPI.h"
#import "FMDBTool.h"
#import "BeeCloud+Utils.h"
#import <AdSupport/ASIdentifierManager.h>
#import "JPUSHService.h"
#import "UMFeedback.h"
#import <AudioToolbox/AudioToolbox.h>
#import "KLManualTableViewController.h"
#import "HemaConst.h"
#import "Masonry.h"
#import "KLApplyKeysMsgTableViewController.h"
#import "KLTabBarVC.h"
#import "Alert.h"

@interface AppDelegate ()<UITabBarControllerDelegate>
{
    UIScrollView *scrollView;
    KLManualTableViewController *manualOpenLcok;
    KLApplyKeysMsgTableViewController *applyKeysMsgVC;
    BOOL appActive;
}
@end

static NSArray *_dateBaseArray;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UMFeedback setAppkey:@"57675ccae0f55a59af000fd2"];
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"1df94f4fc8506353dee4b239"
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];
    //注册通知
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加修改密码通知，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(changePassword:) name:@"changePassword" object:nil];
    [center addObserver:self selector:@selector(initLoginViewController) name:@"loginOut" object:nil];
    [center addObserver:self selector:@selector(isHaveNewApply:) name:@"isHaveNewApply" object:nil];

    //数据库字段
    _dateBaseArray = [NSArray arrayWithObjects:@"userid",@"username",@"email",@"password",@"nickname",@"mobile",@"avatar",@"validflag",@"score",@"feeaccount",@"deviceid",@"devicetype",@"lastloginversion",@"lastlogintime",@"imgurl0",@"imgurl1",@"state",@"birthday",@"imgurl2",@"sex",@"token",nil];
 
        //第一次登陆时保存用户名密码;默认不自动登录，当用户选择自动登录时，则下次不输入密码登录，除非取消
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    BOOL isAutoLogin = [userDefault boolForKey:@"isAutoLogin"];
    //初始化主界面
    UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
    KLLeftTableViewController *leftTableViewVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"leftTableViewVC"];
    
    self.drawerController = [[MMDrawerController alloc] initWithCenterViewController:[mainStoryboard instantiateViewControllerWithIdentifier:@"navCenter"] leftDrawerViewController:leftTableViewVC];
    
    [self.drawerController setDrawerVisualStateBlock:[MMDrawerVisualState slideAndScaleVisualStateBlock]];
    [self.drawerController setMaximumLeftDrawerWidth:260.0];
    [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModePanningNavigationBar];
    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    //初始化手动开锁界面
    manualOpenLcok = [[KLManualTableViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:manualOpenLcok];
    
    //设置标题
    manualOpenLcok.tabBarItem.title = @"手动";
    manualOpenLcok.tabBarItem.image = [UIImage imageNamed:@"手动"];
    self.drawerController.tabBarItem.title = @"自动";
    self.drawerController.tabBarItem.image = [UIImage imageNamed:@"摇一摇"];
    applyKeysMsgVC = [[KLApplyKeysMsgTableViewController alloc]init];
    applyKeysMsgVC.tabBarItem.title = @"申请";
    applyKeysMsgVC.tabBarItem.image = [UIImage imageNamed:@"申请"];
    
    //初始化tabBarController
    UITabBarController *tabBarVC = [KLTabBarVC sharedTabBarVC];
    [tabBarVC addChildViewController:self.drawerController];
    [tabBarVC addChildViewController:nav];
    [tabBarVC addChildViewController:applyKeysMsgVC];
    NSLog(@"是自动登录:%d",isAutoLogin);
    if (isAutoLogin) {
        //如果是自动登录，后台要自动掉一次登录接口
        NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
        NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
        
        [KLHttpAPI requestLoginResultWithUsername:userName password:passWord completionHandler:^(NSString *responseString) {
            NSDictionary *responseDic = [KLHelp dictionaryWithJsonString:responseString];
            NSDictionary *inforDic = [responseDic objectForKey:@"infor"][0];
            
            NSString *isTrue = [responseDic objectForKey:@"success"];
            if(isTrue.integerValue == 1){
                //拿到登录信息的数据
                NSMutableDictionary *userInfofDic = [NSMutableDictionary dictionaryWithDictionary:inforDic];
                
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                [userDefault setObject:[userInfofDic objectForKey:@"token"] forKey:@"token"];
                [userDefault setObject:[userInfofDic objectForKey:@"username"] forKey:@"userName"];
                [userDefault setObject:[userInfofDic objectForKey:@"mobile"] forKey:@"phoneNumber"];
                [userDefault setObject:[userInfofDic objectForKey:@"id"] forKey:@"userid"];
                
                //将得到的用户信息存入数数据库
                [FMDBTool openDataBase];
                [FMDBTool deleteDataBase];
                for (int i = 0; i < _dateBaseArray.count; i++) {
                    if(i == 0){
                        [FMDBTool insertDataBaseWithKey:_dateBaseArray[i] value:[inforDic objectForKey:@"id"]];
                    }else{
                        [FMDBTool insertDataBaseWithKey:_dateBaseArray[i] value:[inforDic objectForKey:[_dateBaseArray objectAtIndex:i]]];
                    }
                }
            }
        } errorHandler:^(NSString *error) {
        }];
        
        //初始化自动开锁界面
        [self initMainViewController:tabBarVC];
    }else{
        //初始化登录界面
        [self initLoginViewController];
    }

    //判断是不是第一次启动应用
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        NSLog(@"第一次启动");
        //如果是第一次启动的话,使用UserGuideViewController (用户引导页面) 作为根视图
        [self initGuide:self.window];
    }
    
    appActive = YES;
    
    return YES;
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

-(void)applicationDidEnterBackground:(UIApplication *)application{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"enterBackGround" object:nil];
}

//程序挂起之后复原会掉用
- (void)applicationDidBecomeActive:(UIApplication *)application{
    application.applicationIconBadgeNumber = 0;
    
    if(appActive){
        appActive = NO;
    }else{
        //每次从后台进入前台获取一次token
        NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
        NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
        if(userName.length != 0 && passWord.length != 0){
            [KLHttpAPI requestGetTokenWithUsername:userName password:passWord completionHandler:^(NSString *responseString) {
                NSDictionary *responseDic = [KLHelp dictionaryWithJsonString:responseString];
                NSDictionary *inforDic = [responseDic objectForKey:@"infor"][0];
                
                NSString *isTrue = [responseDic objectForKey:@"success"];
                if(isTrue.integerValue == 1){
                    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"loginInitSuccess"];
                    [userDefault setObject:[inforDic objectForKey:@"token"] forKey:@"token"];
                }
            } errorHandler:^(NSString *error) {
            }];
        }
    }
}

-(void)initMainViewController:(UITabBarController *)tabBarVC{
    self.window.rootViewController = tabBarVC;
    [self.window makeKeyAndVisible];
}-(void)isHaveNewApply:(NSNotification *)notify{
    NSDictionary *userInfo = [notify userInfo];
    NSString *new_order = [userInfo objectForKey:@"newApplyCount"];
    if(new_order.integerValue != 0){
        [applyKeysMsgVC.tabBarItem setBadgeValue:new_order];
    }
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    if (![BeeCloud handleOpenUrl:url]) {
        //handle其他类型的url
        NSLog(@"从支付宝返回时的回调");
    }
    return YES;
}

-(void)initLoginViewController{
    KLLoginViewController *logVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"navLogViewController"];
    
    self.window.rootViewController = logVC;
    [self.window makeKeyAndVisible];
}

-(void)changePassword:(id)sender{
    [self initLoginViewController];
    [JRToast showWithText:@"密码修改成功"];
}

#pragma mark - 启动引导页
- (void)initGuide:(UIView *)view{
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height)];
    [scrollView setContentSize:CGSizeMake(UI_View_Width*3, UI_View_Height)];
    [scrollView setPagingEnabled:YES];  //视图整页显示
    [scrollView setBounces:NO]; //避免弹跳效果,避免把根视图露出来
    
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height)];
    [imageview setImage:[UIImage imageNamed:@"引导1"]];
    [scrollView addSubview:imageview];
    UILabel *titlelabel = [[UILabel alloc]init];
    titlelabel.text = @"让手机成为您的钥匙库";
    titlelabel.font = [UIFont systemFontOfSize:20];
    titlelabel.textColor = RGB_UI_COLOR(255, 255, 153);
    [imageview addSubview:titlelabel];
    [titlelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imageview).with.offset(0);
        make.top.mas_equalTo(95);
    }];
    
    UIImageView *imageview1 = [[UIImageView alloc] initWithFrame:CGRectMake(UI_View_Width, 0, UI_View_Width, UI_View_Height)];
    [imageview1 setImage:[UIImage imageNamed:@"引导2"]];
    [scrollView addSubview:imageview1];
    UILabel *titlelabel1 = [[UILabel alloc]init];
    titlelabel1.text = @"能开蓝牙的手机都是好钥匙";
    titlelabel1.font = [UIFont systemFontOfSize:20];
    titlelabel1.textColor = RGB_UI_COLOR(255, 255, 153);
    [imageview1 addSubview:titlelabel1];
    [titlelabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imageview1).with.offset(0);
        make.top.mas_equalTo(95);
    }];
    
    UIImageView *imageview3 = [[UIImageView alloc] initWithFrame:CGRectMake(UI_View_Width*2, 0, UI_View_Width, UI_View_Height)];
    [imageview3 setImage:[UIImage imageNamed:@"引导3"]];
    imageview3.userInteractionEnabled = YES;    //打开imageview3的用户交互;否则下面的button无法响应
    [scrollView addSubview:imageview3];
    UILabel *titlelabel2 = [[UILabel alloc]init];
    titlelabel2.text = @"子钥匙一键发送，权限一键管理";
    titlelabel2.font = [UIFont systemFontOfSize:20];
    titlelabel2.textColor = RGB_UI_COLOR(255, 255, 153);
    [imageview3 addSubview:titlelabel2];
    [titlelabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imageview3).with.offset(0);
        make.top.mas_equalTo(95);
    }];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];//在imageview3上加载一个透明的button
    [button setTitle:@"跳过" forState:UIControlStateNormal];
    [button setTintColor:[UIColor whiteColor]];
    [button setFrame:CGRectMake(UI_View_Width-75, 40, 45, 30)];
    button.layer.borderWidth = 1;
    button.layer.borderColor = [[UIColor whiteColor] CGColor];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 5;
    [button addTarget:self action:@selector(firstLaunch) forControlEvents:UIControlEventTouchUpInside];
    [imageview3 addSubview:button];
    
    [view addSubview:scrollView];
}

-(void)firstLaunch{
    [UIView animateWithDuration:0.3 animations:^{
        scrollView.alpha = 0;
    } completion:^(BOOL finished) {
        [scrollView removeFromSuperview];
    }];
}
@end
